<template>
	<view>
		<view class="address-wrapper" @click="getAddr">
			<view class="address" v-if="addr.userName">
				<view class="receiver">
					<view class="name">收货人：{{addr.userName}}</view>
					<view class="phone-num">{{addr.telNumber}}</view>
					<text class="iconfont icon-arrow-right"></text>
				</view>
				<view class="address-txt">收货地址：{{addr.provinceName+addr.cityName+addr.countyName+addr.detailInfo}}</view>
			</view>
			<!-- 选择地址 -->
			<view class="choose-address" v-else>
				<view>请选择地址</view>
				<text class="iconfont icon-arrow-right"></text>
			</view>
			<view class="flower">
				<image src="/static/images/cart_border@2x.png"></image>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-list">
			<view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="toItem(item.goodsId)">
				<image :src="item.goods_small_logo" alt="">
				</image>
				<view class="right">
					<!-- //item.goodsId去goodsList找一个符合条件的对象,条件对象.goods_id===item.goodsId,然后取对象.goods_name -->
					<text class="text-line2">{{item.goods_name}}</text>
					<view class="btm">
						<text class="price">
							￥
							<text>{{item.goods_price}}</text>
							.00
						</text>
						<view class="goods-num">
							<text>{{item.num}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-fixed" @click="wxPay">
			微信支付({{totalPrice}}.00)
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 收货地址
				addr: uni.getStorageSync('addr') || {},
				goodsList: []
			}
		},
		onLoad(options) {
			// 从立即购买跳转支付,带上商品id
			this.goodsId = parseInt(options.goodsId)
			if (this.goodsId) {
				// 如果立即购买过来,构造一个storage cart
				this.storageCartArr = [{
					goodsId: this.goodsId,
					num: 1
				}]
			} else {
				// 商品id以逗号分隔
				// this.storageCartArr = uni.getStorageSync('cart') || []
				this.storageCartArr = this.$store.state.cart 
				
				// 过滤只保留storage cart里面勾选商品
				this.storageCartArr = this.storageCartArr.filter(item => {
					return item.checked
				})
			}

			let goodsIdArr = this.storageCartArr.map(item => {
				return item.goodsId
			})

			let goodsIdStr = goodsIdArr.join(',')

			// 发请求
			this.queryGoodsList(goodsIdStr)
		},
		computed: {
			totalPrice() {
				//总价格:所有勾选的商品数量*单价之和
				return this.goodsList.reduce((sum, item) => {
					return sum + item.num * item.goods_price
				}, 0)
			},
			// 没有在结构中使用的变量,不要声明为data属性或者计算属性
			// getConsigneeAddr(){
			// 	return this.addr.provinceName+this.addr.cityName+this.addr.countyName+this.addr.detailInfo+
			// 	` ${this.addr.userName} ${this.addr.telNumber}`
			// }
		},
		methods: {
			wxPay() {
				// 判断用户是否选择收货地址
				if (!this.addr.userName) {
					uni.showToast({
						title: '请选择收货地址先',
						icon: 'none'
					})
					return
				}
				// 创建订单
				this.createOrder()
			},
			getConsigneeAddr() {
				return this.addr.provinceName + this.addr.cityName + this.addr.countyName + this.addr.detailInfo +
					` ${this.addr.userName} ${this.addr.telNumber}`
			},
			getFilterGoodsList() {
				return this.goodsList.map(item => {
					return {
						goods_id: item.goodsId,
						goods_number: item.num,
						goods_price: item.goods_price
					}
				})
			},
			async createOrder() {
				// this.token = uni.getStorageSync('token')
				let data = await this.$request({
						url: '/api/public/v1/my/orders/create',
						method: 'POST',
						// header: {
						// 	Authorization: this.token
						// },
						isAuth: true,
						data: {
							order_price: this.totalPrice,
							consignee_addr: this.getConsigneeAddr(),
							goods: this.getFilterGoodsList()
						}
					})

					// 订单创建成功，把勾选的商品从storage去掉;且立即购买跳转不需要处理
					!this.goodsId && this.arrangeStorageCart()
				// 相当于if(!this.goodsId){this.arrangeStorageCart()}

				// 添加Vue实例的属性,相当于全局变量
				this.orderNumber = data.order_number
				// 获取支付参数
				this.doPay()
			},
			// 把勾选的商品从storage去掉
			arrangeStorageCart() {
				this.$store.commit('arrangeCart')
			},
			async doPay() {
				let data = await this.$request({
					url: '/api/public/v1/my/orders/req_unifiedorder',
					method: 'POST',
					isAuth: true,
					// header: {
					// 	Authorization: this.token
					// },
					data: {
						order_number: this.orderNumber
					}
				})
				console.log(data)
				// 弹出支付弹框
				// uni.requestPayment({
				// 	...data.pay,
				// 	success: (res) => {
				// 		uni.showToast({
				// 			title: '支付成功',
				// 		})
				// 	},
				// 	fail: (res) => {
				// 		uni.showToast({
				// 			title: '支付失败',
				// 		})
				// 	}
				// })
				uni.requestPayment({
					...data.pay,
					success: res => {
						uni.showToast({
							title: '支付成功'
						});
						uni.navigateTo({
							url: '/pages/order_result/order_result'
						})
					},
					fail: res => {
						uni.showToast({
							title: '支付失败'
						});
						uni.navigateTo({
							url: '/pages/order_result/order_result?orderNumber=' + this.orderNumber
						})
					},
				});
			},
			async queryGoodsList(goodsIdStr) {
				let _goodsList = await this.$request({
					url: '/api/public/v1/goods/goodslist?goods_ids=' + goodsIdStr
				})

				this.goodsList = this.storageCartArr.map(item => {
					// item.goodsId去goodsList找一个符合条件的对象,条件goodsId相等
					let targetGoods = _goodsList.find(goods => {
						return goods.goods_id === item.goodsId
					})
					return { ...targetGoods,
						...item
					}
				})
			},
			getAddr() {
				// 直接调接获取通讯地址的接口
				uni.chooseAddress({
					success: (res) => {
						console.log(res)
						this.addr = res
						uni.setStorageSync('addr', res)
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.address-wrapper {
		background-color: #fff;
	}

	.address {
		display: flex;
		flex-direction: column;
		padding: 44rpx 30rpx 48rpx 20rpx;

		.receiver {
			display: flex;
			justify-content: space-between;
			margin-bottom: 50rpx;
			position: relative;

			.phone-num {
				margin-right: 40rpx;
			}

			.icon-arrow-right {
				position: absolute;
				top: 8rpx;
				right: 0;
				color: #999;
			}
		}
	}

	.choose-address {
		display: flex;
		padding: 44rpx 30rpx 48rpx 20rpx;
		justify-content: space-between;

		.icon-arrow-right {
			color: #999;
		}
	}

	.flower {
		image {
			height: 16rpx;
			width: 100%;
			display: block;
		}
	}

	.goods-item {
		height: 206rpx;
		background-color: #fff;
		border-top: 1rpx solid #ddd;
		display: flex;
		box-sizing: border-box;
		align-items: center;

		image {
			width: 160rpx;
			height: 160rpx;
			margin-left: 30rpx;
		}

		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			margin: 0 20rpx 0 18rpx;

			.btm {
				display: flex;
				margin-top: 40rpx;
				justify-content: space-between;

				.price {
					color: #eb4450;

					>text {
						font-size: 24px;
					}
				}

				.goods-num {
					display: flex;
					align-items: center;

					button {
						width: 60rpx;
						height: 50rpx;
						box-sizing: border-box;
						display: flex;
						justify-content: center;
						align-items: center;
						border: 4rpx solid #666;
					}

					text {
						margin: 0 30rpx;
					}
				}
			}
		}
	}

	.goods-list {
		position: absolute;
		bottom: 98rpx;
		top: 243rpx;
		width: 100%;
		overflow: auto;
		padding-bottom: 60rpx;
		background-color: #f4f4f4;
	}

	.bottom-fixed {
		position: absolute;
		height: 98rpx;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #1aad19;
		color: #fff;
		line-height: 98rpx;
		text-align: center;
	}
</style>
